/*
 * Hidden Equity LLC
 * Author: Maksym Fedyay, Kyiv, mcsimf@gmail.com
 * Date: 29.02.2012
 */

package com.hiddenequity.acts;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.hiddenequity.conversion_service.ConversionResponseParser;
import com.hiddenequity.conversion_service.ConversionService;
import com.hiddenequity.utils.AppPreferences;
import com.hiddenequity.utils.AuthService;
import com.hiddenequity.utils.Communication;
import com.hiddenequity.utils.DateProcessor;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

public class Act_ConversionList extends Act_Super{
	
	
	private static ArrayList<HashMap<String, String>> conversionList = new ArrayList<HashMap<String, String>>();

	private int dateRangeItem;
	private int statusItem;
		
	Spinner spinnerDateRange;
	Spinner spinnerStatus;
	
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_coversion_list);

        title.setText(getString(R.string.title_conversion_list));
        sub_title.setVisibility(View.GONE);
        
		spinnerDateRange = (Spinner) findViewById(R.id.spin_CampaignDateRange);
		dateRangeItem = AppPreferences.LoadPreferenceInt("dateRange", 0,
				getApplication());
		inflateSpinner(spinnerDateRange, R.array.arr_dateRanges, dateRangeItem);

		spinnerDateRange
				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int pos, long id) {
						try {
							if (pos != dateRangeItem) {
								AppPreferences.SavePreferenceInt("dateRange",
										pos, getApplication());
								dateRangeItem = pos;
								runOperationAsync(OPERATION_GET_LIST, getString(R.string.progress_loading), false);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}

					}

					public void onNothingSelected(AdapterView<?> parent) {
					}

				});

		// Populate status list
		spinnerStatus = (Spinner) findViewById(R.id.spin_CampaignStatus);
		statusItem = AppPreferences.LoadPreferenceInt("status", 0, getApplication());
		inflateSpinner(spinnerStatus, R.array.arr_status, statusItem);

		spinnerStatus
				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int pos, long id) {
						try {
							if (pos != statusItem) {
								AppPreferences.SavePreferenceInt("status", pos,
										getApplication());
								statusItem = pos;
								runOperationAsync(OPERATION_GET_LIST, getString(R.string.progress_loading), false);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}

					}

					public void onNothingSelected(AdapterView<?> parent) {
					}

				});
        
		//Filter toggler
		filterToggler(AppPreferences.LoadPreferenceInt("filterToggle", 0, getApplication()));
		final Button btn_toggleFilter = (Button) findViewById(R.id.btn_toggleFilter);
		btn_toggleFilter.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				LinearLayout filter = (LinearLayout) findViewById(R.id.ll_filter);
				filterToggler(filter.getVisibility());
			}
		});
		
		
		//Set adapter and context menu for listview
		final ListView lv = (ListView) findViewById(R.id.list_conversion);
		lv.setAdapter(conversionListAdapter);
		registerForContextMenu(lv);

//		lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
//				Map<String, String> itemMap = (Map<String, String>) lv.getItemAtPosition(position);
////				if(!itemMap.get("status").equals("DELETED")){
////					Intent intent = new Intent(getBaseContext(), Act_.class);
////					startActivityForResult(intent, REQUEST_NO_REFRESH_REQUIRED);					
////				}
//			}
//		});

		runOperationAsync(OPERATION_GET_LIST, getString(R.string.progress_loading), false);
		
    }//onCreate
	
    
    /*
     * Handles requested activity result
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);
    	
    	filterToggler(AppPreferences.LoadPreferenceInt("filterToggle", 0, getApplication()));
    	
    	if(resultCode == RESPONSE_FINISH_REQUIRED){
			finishActivityWithResult(RESPONSE_FINISH_REQUIRED);
		} else if(resultCode == RESPONSE_GOTO_MAIN_ACTIVITY){
			finishActivityWithResult(RESPONSE_GOTO_MAIN_ACTIVITY);
		} else if(isFilterChanged(statusItem, dateRangeItem)){
			statusItem = AppPreferences.LoadPreferenceInt("status", 0, getApplication());
			dateRangeItem = AppPreferences.LoadPreferenceInt("dateRange", 0, getApplication());
			runOperationAsync(OPERATION_GET_LIST, getString(R.string.progress_refreshing), false);
		} else if(requestCode == REQUEST_REFRESH_REQUIRED && resultCode == RESPONSE_REFRESH_REQUIRED){
			runOperationAsync(OPERATION_GET_LIST, getString(R.string.progress_refreshing), false); 			
		}
    	
		spinnerStatus.setSelection(statusItem);
		spinnerDateRange.setSelection(dateRangeItem);
    	
   	}//onActivityResult  
    
    

	/*
	 * Inflate Option menu called when menu button pressed (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.option_conversion_list, menu);
		return true;
	}// onCreateOptionsMenu

	
	
	/*
	 * Option menu selection handler (non-Javadoc)
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent;

		switch (item.getItemId()) {
			case R.id.refresh_Conversions: 
				runOperationAsync(OPERATION_GET_LIST, getString(R.string.progress_refreshing), false);
				break;
	            
			case R.id.add_Conversion:
				intent = new Intent(this.getApplicationContext(),
						Act_ConversionOperation.class);
				startActivityForResult(intent, REQUEST_REFRESH_REQUIRED);
				break;
	
			case R.id.switch_AccountConversion:
				AuthService.performLogout(getApplication());
				intent = new Intent(this.getApplicationContext(), Act_Login.class);
				startActivityForResult(intent, REQUEST_REFRESH_REQUIRED);
				break;
		}
		
		return super.onOptionsItemSelected(item);
	}// onOptionsItemSelected
 

	
	
	/*
	 * Inflate Context menu when long press occurred (non-Javadoc)
	 * @see android.app.Activity#onCreateContextMenu(android.view.ContextMenu,
	 * android.view.View, android.view.ContextMenu.ContextMenuInfo)
	 */
	//String selectedConversionId;
	//String selectedConversionName;
	private Map<String, String> selectedItem;
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		
		switch (v.getId()) {

		case R.id.list_conversion:
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
			ListView list = (ListView) v;
			selectedItem = (Map<String, String>) list.getItemAtPosition(info.position);
			
			String status = selectedItem.get("status");

			menu.add(0, 1, 0, R.string.conversion_edit_name);
			menu.add(0, 2, 0, R.string.conversion_edit_settings);
			menu.add(0, 3, 0, R.string.conversion_send_snippet);

			if (!status.equals("ENABLED"))
				menu.add(0, 4, 0, R.string.status_active);

			if (!status.equals("DISABLED"))
				menu.add(0, 5, 0, R.string.status_pause);

			if (!status.equals("HIDDEN"))
				menu.add(0, 6, 0, R.string.status_delete);

			break;
		}

		menu.setHeaderTitle(getString(R.string.tit_context_conversion));
	}// onCreateContextMenu

	
	
	/*
	 * Context menu selection handler (non-Javadoc)
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		Intent intent;

		switch (item.getItemId()) {

		case 1:
			intent = new Intent(this.getApplicationContext(),
					Act_ConversionOperation.class);
			intent.putExtra("conversionId", selectedItem.get("id"));
			intent.putExtra("conversionName", selectedItem.get("name"));
			
			startActivityForResult(intent, REQUEST_REFRESH_REQUIRED);
			break;

		case 2:
			intent = new Intent(this.getApplicationContext(),
					Act_ConversionSettings.class);
			intent.putExtra("conversionId", selectedItem.get("id"));
			intent.putExtra("name", selectedItem.get("name"));
			intent.putExtra("category", selectedItem.get("category"));
			intent.putExtra("markupLanguage", selectedItem.get("markupLanguage"));
			intent.putExtra("httpProtocol", selectedItem.get("httpProtocol"));
			intent.putExtra("textFormat", selectedItem.get("textFormat"));
			intent.putExtra("conversionPageLanguage", selectedItem.get("conversionPageLanguage"));
			intent.putExtra("backgroundColor", selectedItem.get("backgroundColor"));
			intent.putExtra("userRevenueValue", selectedItem.get("userRevenueValue"));
			
			startActivityForResult(intent, REQUEST_REFRESH_REQUIRED);
			break;
			
		case 3:
			final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
			emailIntent.setType("text/html");
			emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Conversion tracker code snippet");
			emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, selectedItem.get("snippet"));
			startActivity(Intent.createChooser(emailIntent, "Email:"));

			break;
			
		case 4:
			statusSetTo = STATUS_ACTIVE;
			runOperationAsync(OPERATION_SET_STATUS, getString(R.string.progress_applying), false);
			break;

		case 5:
			statusSetTo = STATUS_PAUSED;
			runOperationAsync(OPERATION_SET_STATUS, getString(R.string.progress_applying), false);
			break;

		case 6:
			statusSetTo = STATUS_DELETED;
			
			new AlertDialog.Builder(this)
					.setTitle(R.string.msg_title_conf_delete)		
					.setMessage(getString(R.string.msg_conf_campaign_delete) + " " + quote + selectedItem.get("name") + quote)
	    			.setPositiveButton(R.string.btn_Yes, deletionConfirmationListener)
		    		.setNegativeButton(R.string.btn_No, deletionConfirmationListener)
		    		.setCancelable(false)
		    		.create()
		    		.show();
			
			break;
		}
		return true;
	}//onContextItemSelected
	

	
	/*
	 * Dialog onClick Listener
	 */
	private DialogInterface.OnClickListener deletionConfirmationListener = new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {

			switch (which){
	        
		        case DialogInterface.BUTTON_POSITIVE:
		        	runOperationAsync(OPERATION_SET_STATUS, getString(R.string.progress_applying), false);
		            break;
	
		        case DialogInterface.BUTTON_NEGATIVE:
		        	//Do nothing on cancel
		            break;
	        }
	        
		}
	};//DialogClickListener
	
	
	
	/*
     * Base adapter for listview
     */
	private BaseAdapter conversionListAdapter = new BaseAdapter() {

		public int getCount() {
			int size = Act_ConversionList.conversionList.size();
			return size;
		}

		public Object getItem(int position) {
			return Act_ConversionList.conversionList.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;

			if (row == null) {
				LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				row = mInflater.inflate(R.layout.list_row_conversion, null);
			}

			TextView conversion_name = (TextView) row.findViewById(R.id.conversion_name);
			
			TextView conversion_category = (TextView) row.findViewById(R.id.conversion_category);
			TextView conversion_markup = (TextView) row.findViewById(R.id.conversion_markup);
			TextView conversion_protocol = (TextView) row.findViewById(R.id.conversion_protocol);
			TextView conversion_textFormat = (TextView) row.findViewById(R.id.conversion_textFormat);
			TextView conversion_language = (TextView) row.findViewById(R.id.conversion_language);
			TextView conversion_color = (TextView) row.findViewById(R.id.conversion_color);
			TextView conversion_userRevenueValue = (TextView) row.findViewById(R.id.conversion_userRevenueValue);
			TextView conversion_snippet = (TextView) row.findViewById(R.id.conversion_snippet);
			
			TextView conversion_category_value = (TextView) row.findViewById(R.id.conversion_category_value);
			TextView conversion_status = (TextView) row.findViewById(R.id.conversion_status);
			TextView conversion_count = (TextView) row.findViewById(R.id.conversion_count);
			TextView conversion_value = (TextView) row.findViewById(R.id.conversion_value);
			TextView conversion_id = (TextView) row.findViewById(R.id.conversion_id);
			ImageView img_campaign_status = (ImageView) row.findViewById(R.id.img_conversion_status);
		
			conversion_category.setText(Act_ConversionList.conversionList.get(position).get("category"));
			conversion_markup.setText(Act_ConversionList.conversionList.get(position).get("markupLanguage"));
			conversion_protocol.setText(Act_ConversionList.conversionList.get(position).get("httpProtocol"));
			conversion_textFormat.setText(Act_ConversionList.conversionList.get(position).get("textFormat"));
			conversion_language.setText(Act_ConversionList.conversionList.get(position).get("conversionPageLanguage"));
			conversion_color.setText(Act_ConversionList.conversionList.get(position).get("backgroundColor"));
			conversion_userRevenueValue.setText(Act_ConversionList.conversionList.get(position).get("userRevenueValue"));			
			conversion_snippet.setText(Act_ConversionList.conversionList.get(position).get("snippet"));
			
			conversion_name.setText(Act_ConversionList.conversionList.get(position).get("name"));
			conversion_count.setText(Act_ConversionList.conversionList.get(position).get("numConversionEvents"));
			conversion_value.setText(Act_ConversionList.conversionList.get(position).get("conversionValue"));
			conversion_id.setText(Act_ConversionList.conversionList.get(position).get("id"));
			
			String category = Act_ConversionList.conversionList.get(position).get("category");
			
			if(category.equals("DEFAULT")){
				conversion_category_value.setText("Other");	
			} else if(category.equals("PAGE_VIEW")){
				conversion_category_value.setText("View of a key page");
			}else if(category.equals("PURCHASE")){
				conversion_category_value.setText("Purchase/Sale");
			}else if(category.equals("SIGNUP")){
				conversion_category_value.setText("SignUp");
			} else if(category.equals("LEAD")){
				conversion_category_value.setText("Lead");
			}

			String status = Act_ConversionList.conversionList.get(position).get("status");
			conversion_status.setText(status);
			
			if(status.equals("ENABLED")){
				img_campaign_status.setImageResource(R.drawable.enable);
			} else if(status.equals("DISABLED")){
				img_campaign_status.setImageResource(R.drawable.pause);
			} else if(status.equals("HIDDEN")){
				img_campaign_status.setImageResource(R.drawable.delete);
			}

			return row;
		}
	};//campaignListAdapter
	
	
	
	/*
	 * Async operation
	 */
	private void runOperationAsync(final int operation, String message, boolean overlap) {

		// Stop if thread is alive
		if (thread.isAlive() && !overlap)
			return;

		// Show progress dialog
		final ProgressDialog progressDialog = ProgressDialog.show(this, "",
				message, true);

		// Check if Internet connection alive
		if (!isConnectionAvalable()) {
			progressDialog.dismiss();
			return;
		}

		thread = new Thread() {
			public void run() {
				// Perform authentication
				new AuthService(Act_ConversionList.this, getApplication());

				// Perform operation
				if (AuthService.authToken != null) {
					try {
						switch (operation) {
						case OPERATION_GET_LIST:
							Act_ConversionList.this.getConversionList();
							Act_ConversionList.this.getTip();
							break;

						case OPERATION_SET_STATUS:
							Act_ConversionList.this.setConversionStatus();
							break;
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				// Perform postoperation
				Act_ConversionList.this.runOnUiThread(new Runnable() {
					public void run() {

						progressDialog.dismiss();

						if (AuthService.authToken != null) {

							showOperationError(R.string.msg_title_error,
									responseErrorString);

							switch (operation) {
							case OPERATION_GET_LIST:
								conversionListAdapter.notifyDataSetChanged();
								showTip();
								break;

							case OPERATION_SET_STATUS:
								runOperationAsync(OPERATION_GET_LIST, getString(R.string.progress_refreshing), true);
								break;
							}

						} else {
							Intent intent = new Intent(
									Act_ConversionList.this
											.getApplicationContext(),
									Act_Login.class);
							startActivityForResult(intent,
									REQUEST_REFRESH_REQUIRED);
						}
					}
				});
			}
		};
		thread.start();

	}//runOperationAsync



	protected void setConversionStatus() {
		String resp = Communication.postSOAP(
				ConversionService .URL_CONVERSION_SERVICE, 
				ConversionService.setConversionTrackerStatus(selectedItem.get("id"), statusSetTo)
    		);

    	ConversionResponseParser parser = new ConversionResponseParser(resp);

    	responseErrorString = parser.checkForErrors();
	}

	
	
	protected void getConversionList() {
		conversionList.clear();
		
		String resp = Communication.postSOAP(
				ConversionService .URL_CONVERSION_SERVICE, 
				ConversionService.getConversionTrackerList(DateProcessor.getDateRange(dateRangeItem),
						statusItem)
    		);

    	ConversionResponseParser parser = new ConversionResponseParser(resp);
    	
    	conversionList.addAll(parser.getConversionList());
    	
    	responseErrorString = parser.checkForErrors();
	}

}
